package main

import (
	"context"
	"fmt"
	"sync"

	_ "github.com/mbobakov/grpc-consul-resolver"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	proto "mxshop_srvs/inventory_srv/proto/gen/v1"
	"mxshop_srvs/inventory_srv/setting"
)

var conn *grpc.ClientConn

func InitSrvConn() (err error) {
	conf := setting.Conf.ConsulConfig

	// 建立RPC连接
	conn, err = grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s", conf.Host, conf.Port, conf.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		return err
	}
	return nil
}

// generateInventory 生成库存
func generateInventory() {
	for i := 421; i < 841; i++ {
		_, err := proto.NewInventoryClient(conn).SetInv(context.Background(), &proto.GoodsInvInfo{
			GoodsId: int32(i),
			Num:     100,
		})
		if err != nil {
			fmt.Printf("%v\n", err)
		}
	}
}

// sell 扣减库存
func sell(wg *sync.WaitGroup) {
	defer wg.Done()
	_, _ = proto.NewInventoryClient(conn).Sell(context.Background(), &proto.SellInfo{
		GoodsInfo: []*proto.GoodsInvInfo{
			{GoodsId: 421, Num: 1},
			{GoodsId: 422, Num: 1},
		},
	})
}

// reBack 归还库存
func reBack(wg *sync.WaitGroup) {
	defer wg.Done()
	_, _ = proto.NewInventoryClient(conn).ReBack(context.Background(), &proto.SellInfo{
		GoodsInfo: []*proto.GoodsInvInfo{
			{GoodsId: 421, Num: 1},
		},
	})
}

func main() {
	setting.Init()
	err := InitSrvConn()
	if err != nil {
		panic(err)
	}

	// generateInventory() // 生成库存

	num := 20
	var wg sync.WaitGroup

	// 模拟并发扣减库存
	for i := 0; i < num; i++ {
		wg.Add(1)
		go sell(&wg)
	}

	// 模拟并发归还库存
	// for i := 0; i < num; i++ {
	// 	wg.Add(1)
	// 	go reBack(&wg)
	// }

	wg.Wait()
}
